package Leetcode第一期;

import java.lang.reflect.Field;

/**
 * @author : K k
 * @date : 10:57 2020/8/19
 */
public class 实现strStr_28 {
    public static void main(String[] args) {
        /*String A="hello,world";
        String B="ell";
        int res=strStr(A,B);
        System.out.println(res);*/

        String s1="hll1";
        String s2="h22";
        String s3="h123";

        ClassLoader classLoader = s1.getClass().getClassLoader();
        try {
            Class<String> stringClass = String.class;
            Object o = stringClass.newInstance();
            Field value = o.getClass().getDeclaredField("value");
            value.setAccessible(true);
            char[] s = (char[]) value.get("s111ss");
            System.out.println(s[1]);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*public static int strStr1(String haystack, String needle){
        int j=0;

    }*/

    public static int strStr(String haystack, String needle) {
        if (needle.length() == 0) {
            return 0;
        }
        int[] next = getNext(needle);
        int i = 0, j = 0;

        while (i < haystack.length() && j < needle.length()) {
            if (j == -1 || haystack.charAt(i) == needle.charAt(j)) {
                i++;
                j++;
            } else {
                j = next[j];
            }
        }

        if (j == needle.length()) {
            return i - j;
        }

        return -1;
    }


    //实现Next数组 求前后公共串长度
    public static int[] getNext(String str){
        int[] next=new int[str.length()];
        next[0]=-1;
        int j=-1;
        int i=0;
        char[] array=str.toCharArray();

        while (i<array.length-1){
            if (j==-1 || array[i]==array[j]){
                next[++i]=++j;
            }else {
                j=next[j];  //若不相等且j=0 则j置为1 为的是让i前进
            }
        }
        return next;
    }
}
